package com.zego.base.http;

import com.zego.base.http.request.HttpResponse;
import com.zego.base.http.request.RequestComplete;
import com.zego.base.http.request.UrlParam;
import com.zego.manager.ModuleMgr;
import com.zego.zegowawaji_server.ZegoApplication;
import com.zego.zegowawaji_server.service.socket.TCPConstant;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Http请求工具类
 * Created by Su on 2017/12/16.
 */
public class RequestMgr {
    public static long gameId = 0;  // 每局游戏id
    public static String cookieVerCode = "";   // 用户cookie, gameOver接口使用
    private static long rid = -1;   // 房间id号

    /**
     * 通知服务端房间状态
     *
     * @param status 房间状态 1:当前空闲 -1：游戏中 -2:故障
     */
    public static void reqRoomStatus(int status) {
        Map<String, Object> postParam = new HashMap<>();
        postParam.put("rid", rid <= 0 ? TCPConstant.getServerID() : rid);
        postParam.put("wwj_status", status);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqRoomStatus, postParam, null);
    }

    /**
     * 结束游戏时通知服务端
     *
     * @param take 1: 成功抓到  -1：没有抓到
     */
    public static void reqGameOver(int take) {
        Map<String, Object> postParam = new HashMap<>();
        postParam.put("game_id", gameId);
        postParam.put("take", take);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqGameOver, postParam, null);
    }

    private static int num = 0;

    /**
     * 根据IMEI获取娃娃机Rid
     */
    public static void reqWwjID() {
        Map<String, Object> getParam = new HashMap<>();
        getParam.put("imei", ZegoApplication.deviceId);
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqWwjID, getParam, new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                if (!response.isOk() && !response.isCache()) {
                    if (num < 2) {
                        num++;
                        reqWwjID();
                    } else {
                        num = 0;
                    }
                    return;
                }
                num = 0;
                JSONObject jsonObject = response.getResponseObject();
                rid = jsonObject.optLong("Id");
                TCPConstant.setServerId(rid);
            }
        });
    }
}
